package xin.nick.cloud.email.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Nick
 * @date 2021/8/1
 * @description
 */
@Component
@Slf4j
public class EmailSender {

    /**
     * 记录邮件发送的时间
     */
    private static Map<String, Long> emailSendTimeMap = new HashMap<>();

    /**
     * 发送的间隔 60S
     */
    private static final Long SEND_INTERVAL = 60L * 1000L;

    @Autowired
    private JavaMailSender javaMailSender;

    @Async
    public void sendEmail(String email, String code) {

        // 限制一分钟只能发送一次
//        Long currentTime = System.currentTimeMillis();
//        Long emailSendTime = emailSendTimeMap.get(email);
//        if (Objects.isNull(emailSendTime)) {
//            emailSendTime = currentTime;
//        }
//        emailSendTimeMap.put(email, emailSendTime);
//        Long limitTIme = emailSendTime + SEND_INTERVAL;
//        if (currentTime.compareTo(limitTIme) < 0) {
//            log.warn("发送的时间太短了啦: {}:{}", email, code);
//            return;
//        }

        String content = "旅行者你好，你的验证码是: " + code + " 请尽快验证哦";
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("1879789522@qq.com");
            message.setTo(email);
            message.setSubject("主题：验证邮件！");
            message.setText(content);
            javaMailSender.send(message);
            log.info("发送邮件验证码成功 {}:{}",email, code);
        }catch (Exception e){
            log.error("发送邮件异常啦", e);
        }
    }
}
